package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.common.MyTouch;
import com.loveto.constant.LovetoConstant;
import com.loveto.model.TournamentInfo;

public class LovotoMainActivity extends BaseActivity implements View.OnClickListener, View.OnTouchListener, OnItemSelectedListener {
	// 여기에서 쓰이는 상수
	private static final String GENDER_STR = "전체성별|남성|여성";
	private static final String ORDER_STR = "최신순|인기순|마감순";
	private static final int DIALOG_FIRST_BONUS = 1;
	private static final int GET_LIST_PER_ONETIME = 3;
	
	// 사용하는 변수들
	private LinearLayout contentMain; // 전체 레이아웃 // LinearLayout
	private ProgressDialog progressDialog; // 프로그레스다이얼로그
	//private List<TournamentInfo> tournamentInfoList; // data // 일단 필요없어서 주석처리
	private String clientLocal;
	private String isLocalSearchDetailStr;
	private String clientGender;
	private String clientOrder;
	private String isGetFirstBonus;
	private int firstBonus;
	private int newMessageCnt = 0;
	private int not_select_winner_tournamentID = 0;
	private int not_view_winner_tournamentID = 0;
	
	private String memberid;
	private String local;
	private String local_detail;
	
	private Dialog customDialogInstance;
	private boolean isShowPopupFistBonus;
	
	private Handler myHandler = new Handler();
	private List<RelativeLayout> tournamentInfoLayoutList; // 하나의 row Layout 들을 간직한 List
	private LinearLayout contentMainInner;
	private List<String> photoUrlList = null;
	
	private boolean isGetListFirst;
	private boolean isHaveMoreList;
	private int startRow;
	private String firstRequestDate;
	private String resultType;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_main);
		
		/*SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		Editor editor = pref.edit();
		editor.putString("memberid", "색녀");
		editor.putString("gender", "F");
		editor.putString("local", "서울");
		editor.putString("age", "30");
		editor.commit();*/
		
		Log.d("tag","LovetoMain Start");
		
		// 초기화
		contentMain = (LinearLayout)findViewById(R.id.content_main);
		progressDialog = new ProgressDialog(LovotoMainActivity.this);
		//tournamentInfoList = new ArrayList<TournamentInfo>(); // 일단 필요없어서 주석처리
		isShowPopupFistBonus = false;
		isGetListFirst = true;
		isHaveMoreList = false;
		startRow = 0;
		firstRequestDate = "";
		
		//로컬에서 정보 받아오기
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "");
		local = pref.getString("local", "");
		local_detail = pref.getString("local_detail", "");
		clientLocal = pref.getString("clientLocal", "전체지역");
		clientGender = pref.getString("clientGender", "전체성별");
		clientOrder = pref.getString("clientOrder", "최신순");
		isLocalSearchDetailStr = "N";
		
		Log.d("tag","로컬정보 받아오기");
		
		//전 액티비티에서 정보 받아오기
		Intent intent = getIntent();
		isGetFirstBonus = intent.getStringExtra("isGetFirstBonus");
		firstBonus = intent.getIntExtra("firstBonus", 0);
		
		// 터치 리스너 달기 // 버튼
		RelativeLayout footer = (RelativeLayout)findViewById(R.id.btn_footer02);
		footer.setOnTouchListener(this);
		footer = (RelativeLayout)findViewById(R.id.btn_footer03);
		footer.setOnTouchListener(this);
		footer = (RelativeLayout)findViewById(R.id.btn_footer04);
		footer.setOnTouchListener(this);
		footer = (RelativeLayout)findViewById(R.id.btn_footer05);
		footer.setOnTouchListener(this);

		// 클릭 리스너 달기 // 버튼
		ImageButton openTournamentButton = (ImageButton)findViewById(R.id.open_tournament);
		openTournamentButton.setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.btn_footer_login)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.btn_footer_explain)).setOnClickListener(this);
		((ImageView)findViewById(R.id.btn_list_end)).setOnClickListener(this);
		
		// 셀렉트 리스너 달기 // 스피너
		Spinner spinner = (Spinner)findViewById(R.id.localspinner);
		spinner.setOnItemSelectedListener(this);
		spinner = (Spinner)findViewById(R.id.genderspinner);
		spinner.setOnItemSelectedListener(this);
		spinner = (Spinner)findViewById(R.id.sortspinner);
		spinner.setOnItemSelectedListener(this);
		
		//스피너 세팅
		setSpinner();
		
		// 토너먼트 리스트 셋팅
		if (isNetworkAvailable()) {
			setTournamentList();
			getNewMessage();
			//new SetTournamentListTask().execute(clientLocal, clientGender, clientOrder);
		} else {
			showSimpleAlertForNetwork(); 
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		
		//푸터 세팅 (로그인 상태에 따라 다르게 보여줌.)
		setFooter();
		
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		RelativeLayout v_parent;
		TextView v_userID;
		String userID;
		switch (v.getId()) {
			case R.id.open_tournament:
				gotoOpenTournament();
				break;
			case R.id.tourlist_userinfo_text:
				v_parent = (RelativeLayout)v.getParent();
				v_userID = (TextView)v_parent.findViewById(R.id.userID);
				userID = (String)v_userID.getText();
				intent = new Intent(LovotoMainActivity.this, UserinfoViewOthersActivity.class);
				intent.putExtra("memberid_other", userID);
				intent.putExtra("lookingTarget", "TournamentMaker");
				startActivity(intent);
				break;
			case R.id.tourlist_photo:
				v_parent = (RelativeLayout)v.getParent();
				v_userID = (TextView)v_parent.findViewById(R.id.userID);
				userID = (String)v_userID.getText();
				intent = new Intent(LovotoMainActivity.this, UserinfoViewOthersActivity.class);
				intent.putExtra("memberid_other", userID);
				intent.putExtra("lookingTarget", "TournamentMaker");
				startActivity(intent);
				break;
			case R.id.tourinfo_talkbox:
				//영역에 적혀있는 텍스트을 읽고 다음 엑티비티에 전달함.
				v_parent = (RelativeLayout)v.getParent();
				TextView text_id = (TextView)v_parent.findViewById(R.id.tournamentID);
				String tournemant_id = (String)text_id.getText();
				intent = new Intent(LovotoMainActivity.this, InfoTournamentActivity.class);
				intent.putExtra("tournamentID", tournemant_id);
				startActivity(intent);
				break;
			case R.id.tourinfo_arrow:
				//영역에 적혀있는 텍스트을 읽고 다음 엑티비티에 전달함.
				v_parent = (RelativeLayout)v.getParent();
				TextView text_id2 = (TextView)v_parent.findViewById(R.id.tournamentID);
				String tournemant_id2 = (String)text_id2.getText();
				intent = new Intent(LovotoMainActivity.this, InfoTournamentActivity.class);
				intent.putExtra("tournamentID", tournemant_id2);
				startActivity(intent);
				break;
			case R.id.btn_footer_login:
				finish();
				intent = new Intent(LovotoMainActivity.this, LoginMainActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_footer_explain:
				intent = new Intent(LovotoMainActivity.this, ExplainTournamentActivity.class);
				startActivity(intent);
				break;
			case R.id.btn_list_end:
				if (isHaveMoreList && isNetworkAvailable()) {
					setTournamentList();
				} else if (isHaveMoreList) {
					showSimpleAlertForNetwork(); 
				}
				break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
			case R.id.btn_footer01:
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					v.setBackgroundResource(R.drawable.btn_footer_touch);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
						gotoActive(LovotoMainActivity.class, v, R.drawable.btn_footer_unselected);
					} else {
						v.setBackgroundResource(R.drawable.btn_footer_unselected);
					}
				}
				break;
			case R.id.btn_footer02:
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					v.setBackgroundResource(R.drawable.btn_footer_touch);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
						gotoActive(JoinedTournamentListActivity.class, v, R.drawable.btn_footer_unselected);
					} else {
						v.setBackgroundResource(R.drawable.btn_footer_unselected);
					}
				}
				break;
			case R.id.btn_footer03:
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					v.setBackgroundResource(R.drawable.btn_footer_touch);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
						gotoActive(MessageMainActivity.class, v, R.drawable.btn_footer_unselected);
					} else {
						v.setBackgroundResource(R.drawable.btn_footer_unselected);
					}
				}
				break;
			case R.id.btn_footer04:
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					v.setBackgroundResource(R.drawable.btn_footer_touch);
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
						gotoActive(UserinfoViewMineActivity.class, v, R.drawable.btn_footer_unselected);
					} else {
						v.setBackgroundResource(R.drawable.btn_footer_unselected);
					}
				}
				break;
			case R.id.btn_footer05:
				if (event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundResource(R.drawable.btn_footer_touch);
				}
				else if (event.getAction() == MotionEvent.ACTION_UP){
					if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
						gotoActive(SetupMainActivity.class, v, R.drawable.btn_footer_unselected);
					} else {
						v.setBackgroundResource(R.drawable.btn_footer_unselected);
					}
				}
				break;
		}
		return true;
	}

	//화면 전환 시켜주기
	private void gotoActive(Class<?> targetClass, View v, int d) {
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		String memberid = pref.getString("memberid", "");
		Log.d("tag", "memberid : " + memberid);
		//Log.d("tag", "memberid.length() : " + memberid.length());
		if(!"LoginMainActivity".equals(targetClass.getName()) && memberid.length() == 0 ) {
			Intent intent = new Intent(LovotoMainActivity.this, LoginMainActivity.class);
			startActivity(intent);
		} else {
			Intent intent;
			intent = new Intent(LovotoMainActivity.this, targetClass);
			startActivity(intent);
			v.setBackgroundResource(d);	
		}
	}
	
	//화면 전환 시켜주기
		private void gotoActive(Class<?> targetClass) {
			//Log.d("tag", "memberid.length() : " + memberid.length());
			if(!"LoginMainActivity".equals(targetClass.getName()) && memberid.length() == 0 ) {
				Intent intent = new Intent(LovotoMainActivity.this, LoginMainActivity.class);
				startActivity(intent);
			} else {
				Intent intent;
				intent = new Intent(LovotoMainActivity.this, targetClass);
				startActivity(intent);
			}
		}

	
	
	// spinner // 지역, 성별, 정렬방법 // 주의 : onCreate 때도 이벤트실행함.
	@Override
	public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
		// TODO Auto-generated method stub
		
		// 검색어를 TextView에 셋팅
		String selectedText = parent.getItemAtPosition(position).toString();
		Log.d("tag", "spinner String : " + selectedText);

		//현재 로컬의 값과 같은 값이 선택 되었다면 중지
		if(clientLocal.equals(selectedText) || clientGender.equals(selectedText) || clientOrder.equals(selectedText)) {
			Log.d("tag", "이미 선택 된 스피너임");
			return;
		}
		
		
		if(selectedText == null || selectedText == "") {
			viewToast("Spinner 오류!!");
			return ;
		}
		
		// 텍스트뷰 init
		TextView local_textview = (TextView) findViewById(R.id.local_textview);
		TextView gender_textview = (TextView) findViewById(R.id.gender_textview);
		TextView order_textview = (TextView) findViewById(R.id.order_textview);
		
		//프리퍼런스 init
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		Editor editor = pref.edit();
		
		//지역 스피너 세팅
		String[] localNameArray = getResources().getStringArray(R.array.local_name_array_for_spinner);
		if (selectedText.equals("내주변 (" + local_detail + ")")) {
			isLocalSearchDetailStr = "Y";
			local_textview.setText(local_detail);
			clientLocal = selectedText;
			editor.putString("clientLocal", clientLocal);
			editor.commit();
		}
		for (int i = 0; i < localNameArray.length;i++) {
			if (localNameArray[i].equals(selectedText)) {
				isLocalSearchDetailStr = "N";
				if (selectedText.equals("전체지역")) {
					local_textview.setText("지역");
				} else {
					local_textview.setText(selectedText);
				}
				clientLocal = selectedText;
				editor.putString("clientLocal", clientLocal);
				editor.commit();
			}
		}
		
		//나머지 스피너 세팅
		if (selectedText.matches(GENDER_STR)) {
			if (selectedText.equals("전체성별")) {
				gender_textview.setText("성별");
			} else {
				gender_textview.setText(selectedText);
			}
			clientGender = selectedText;
			editor.putString("clientGender", clientGender);
			editor.commit();
		} else if (selectedText.matches(ORDER_STR)) {
			order_textview.setText(selectedText);
			clientOrder = selectedText;
			editor.putString("clientOrder", clientOrder);
			editor.commit();
		}
		
		// 토너먼트 리스트 셋팅
		if (isNetworkAvailable()) {
			Log.d("tag", "Get list by onItemSelected");
			isHaveMoreList = false;
			isGetListFirst = true;
			startRow = 0;
			setTournamentList();
			// new SetTournamentListTask().execute(clientLocal, clientGender,
			// clientOrder);
		} else {
			showSimpleAlertForNetwork();
			// new SetTournamentListTask().execute(local, gender, order);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}
	
	//비로그인 시 푸터를 다르게 보여줌.
	private void setFooter() {
		if ("".equals(memberid)) {
			((LinearLayout)findViewById(R.id.footer_logined)).setVisibility(LinearLayout.GONE);
			((LinearLayout)findViewById(R.id.footer_unlogined)).setVisibility(LinearLayout.VISIBLE);
		}
	}
	
	//상황에 맞는 팝업을 보여줌.
	private void showPopups() {
		
		//첫 가입 유저인 경우 축하보너스
		if ("N".equals(isGetFirstBonus) && !isShowPopupFistBonus) {
			isShowPopupFistBonus = true;
			showDialog(DIALOG_FIRST_BONUS);
		}
		
	}
	
	//커스텀 다이얼로그 띄우기
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		dialog = null;
		if (id == DIALOG_FIRST_BONUS) {
			dialog = getDialogFirstBonus();
			customDialogInstance = dialog;
		}
		return dialog;
	}

	private Dialog getDialogFirstBonus() {
		AlertDialog.Builder builder;
		AlertDialog alertDialog;

		// 팝업 레이아웃 설정
		RelativeLayout layout = (RelativeLayout) getLayoutInflater().inflate(
				R.layout.loveto_dialog_bonus_point, null);
		// 팝업 글 수정
		((TextView)layout.findViewById(R.id.text_coin)).setText("+" + firstBonus);
		((TextView)layout.findViewById(R.id.text_celebrate)).setText("가입 보너스로 " + firstBonus + "클로버를 지급해드립니다! \n 토너먼트 첫 참여 성공 시 추가 보너스가 있으니 꼭 참여해보세요!");

		TextView okButton = (TextView) layout.findViewById(R.id.btn_ok);
		okButton.setOnClickListener(new OnClickListener() {
			// 구매 버튼 처리
			@Override
			public void onClick(View v) {
				customDialogInstance.dismiss();
				showPopups();
			}
		});

		builder = new AlertDialog.Builder(this);
		builder.setView(layout);
		alertDialog = builder.create();

		return alertDialog;
	}
	
	private void gotoOpenTournament() {
		//로컬에서 정보 받아오기
		SharedPreferences prefUser = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		String local = prefUser.getString("local", "");
		String age = prefUser.getString("age", ""); 
		String job = prefUser.getString("job", "");
		String height = prefUser.getString("height", "");
		String photo_url1 = prefUser.getString("photo_url1", "");
		
		StringBuffer unInput = new StringBuffer();
		if ("".equals(local) || "null".equals(local)) {
			unInput.append("지역 ");
		}
		if ("".equals(age) || "null".equals(age)) {
			unInput.append("나이 ");
		}
		if ("".equals(job) || "null".equals(job)) {
			unInput.append("직업 ");
		}
		if ("".equals(height) || "null".equals(height)) {
			unInput.append("키 ");
		}
		if ("".equals(photo_url1) || "null".equals(photo_url1)) {
			unInput.append("기본사진 ");
		}
		
		//기본 사진과 기본 정보 입력이 되어있지 않으면 주최 불가. (DB에 있는 값을 그대로 String 으로 저장 될 때 null 로 저장 될 수 있기 때문에 'null' 도 같이 검사.)
		if ("".equals(local) || "".equals(age) || "".equals(job) || "".equals(height) || "".equals(photo_url1) || "null".equals(local) || "null".equals(age) || "null".equals(job) || "null".equals(height) || "null".equals(photo_url1)) {
			showSimpleAlertAndMoveChoice("프로필에 기본사진 1장과 기본정보를 입력해야 주최가 가능합니다. 프로필을 입력하기 위해 이동하시겠습니까? \n [ 필요 정보: " + unInput.toString() + "]", LovotoMainActivity.this, UserinfoViewMineActivity.class,"이동");
			return;
		}
		
		SharedPreferences prefTournament = getSharedPreferences("tournamentMakeInfo", Activity.MODE_PRIVATE);
		Editor editor = prefTournament.edit();
		editor.clear();
		editor.commit();
		gotoActive(OpenTournamentMainActivity.class);
	}
	
	private void showSimpleAlertForNetwork() {
		
		String msg = "인터넷 연결이 되어있지않아 정보를 불러올 수 없습니다.";
	   	new AlertDialog.Builder(this)
	   	.setMessage(msg)
	   	.setPositiveButton("다시 시도", new DialogInterface.OnClickListener()
	   	{
	   		@Override
	   		public void onClick(DialogInterface dialog, int which)
	   		{
	   			if (isNetworkAvailable()) {
	   				dialog.dismiss();
	   				setTournamentList();
	   				getNewMessage();
	   				//new SetTournamentListTask().execute(clientLocal, clientGender, clientOrder);
	   			} else {
	   				showSimpleAlertForNetwork();
	   			}
	   		}
	   	})
	   	.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		}).show();
		
	}
	
	private void showSimpleAlertForSelectOrViewWinner() {
		String title;
		String msg;
		if (not_select_winner_tournamentID != 0) {
			title = "토너먼트 주최완료!";
			msg = "주최 한 토너먼트의 마감시간이 완료되어 우승자를 결정해야합니다. 이동하시겠습니까?";
		} else {
			title = "우승자 결정완료!";
			msg = "참여 한 토너먼트의 우승자 결정이 완료되었습니다. 결과를 보기위해 이동하시겠습니까?";
		}
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(msg)
		.setPositiveButton("이동", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				if (isNetworkAvailable()) {
					dialog.dismiss();
					int gotoTournamentID = 0;
					if (not_select_winner_tournamentID != 0) {
						gotoTournamentID = not_select_winner_tournamentID;
					} else {
						gotoTournamentID = not_view_winner_tournamentID;
					}
					Intent intent = new Intent(LovotoMainActivity.this, InfoTournamentActivity.class);
					intent.putExtra("tournamentID", "" + gotoTournamentID);
					startActivity(intent);
					
				} else {
					dialog.dismiss();
					showSimpleAlertForNetwork();
				}
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		}).show();
		
	}
	
	private void setTournamentList() {
		progressDialog.setMessage("리스트를 불러오고 있습니다.");
		progressDialog.show();
		
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				// 하나의 row Layout 들을 간직한 List 초기화
				tournamentInfoLayoutList = new ArrayList<RelativeLayout>();
				// 안에 들어갈 레이아웃 // 한번에 리스트를 노출하기 위하여
				contentMainInner = new LinearLayout(LovotoMainActivity.this);
				contentMainInner.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				contentMainInner.setOrientation(LinearLayout.VERTICAL);
				Log.d("tag", "sendTalkMessage() start");
				
				try {
					
					StringBuffer URL = new StringBuffer();
					URL.append(LovetoConstant.MAIN_TOURNAMENT_LIST_URL);
					if (isLocalSearchDetailStr.equals("Y")) {
						URL.append("?local=").append(local_detail);
					} else {
						URL.append("?local=").append(clientLocal);
					}
					URL.append("&gender=").append(clientGender);
					URL.append("&order=").append(clientOrder);
					URL.append("&memberid=").append(memberid);
					URL.append("&startRow=").append(startRow);
					URL.append("&firstRequestDate=").append(URLEncoder.encode(firstRequestDate, "UTF-8"));
					URL.append("&isLocalSearchDetailStr=").append(isLocalSearchDetailStr);
					Log.d("tag", "URL: " + URL.toString());
					//서버에서 정보 받아오기
					String jsonText = JsonUtils.getStringFromUrl(URL.toString());
					Log.d("tag", "jsonText: " + jsonText);
					JSONObject getObject = new JSONObject(jsonText);
					resultType = getObject.getString("resultType");
					Log.d("tag", "resultType: " + resultType);
					//firstRequestDate 는 resultType 이 refresh 일 때 서버에서 한 번 받아옴.
					if ("refresh".equals(resultType)) {
						firstRequestDate = getObject.getString("nowDate");
						startRow = 0;
					}
					
					JSONArray jsonArray = getObject.getJSONArray("list");
					int jsonArrayLen = jsonArray.length();
					//받아온 리스트 개수가 30개가 넘으면 더 받아올 리스트가 있다고 판단.
					if (jsonArrayLen > GET_LIST_PER_ONETIME) {
						isHaveMoreList = true;
						startRow = startRow + GET_LIST_PER_ONETIME;
					} else {
						isHaveMoreList = false;
					}
					Log.d("tag", "jsonArray: " + jsonArray.toString());

					// 사진을 전체 다운로드를 위하여 // 초기화
					photoUrlList = new ArrayList<String>(jsonArrayLen);

					for (int i = 0; i < jsonArrayLen; i++) {
						JSONObject object = jsonArray.getJSONObject(i);
						// Log.d("tag", "" + object.toString());
						TournamentInfo tournamentInfo = new TournamentInfo(
								object.getInt("tournamentid"),
								object.getString("tournament_title"),
								object.getInt("participant_cnt"),
								object.getString("tournament_maker_memberid"),
								object.getString("answer_endtime"), 
								object.getString("regdate"), 
								object.getString("local"),
								object.getString("local_detail"),
								object.getString("age"),
								object.getString("gender"),
								object.getString("day"),
								object.getString("hour")
								);

						// 데이터 저장 // 일단 필요없어서 주석처리
						// tournamentInfoList.add(tournamentInfo);
						// 하나의 row 만들기
						RelativeLayout tournamentInfoLayout = makeRelativeLayout(
								tournamentInfo);
						// 사진 전체 다운로드를 위하여, 마지막 1개는 리스트에 넣지 않음. (리스트가 더 있는지 확인하기 위한 가라데이터 이므로)
						if (i != GET_LIST_PER_ONETIME) {
							tournamentInfoLayoutList.add(tournamentInfoLayout);
							contentMainInner.addView(tournamentInfoLayout);
						}
						
					}

				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} catch (JSONException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} finally {

					// 뷰 한번에 넣기
					myHandler.post(new Runnable() {
						@Override
						public void run() { 
							//리프레시면 뷰 지워줌.
							if ("refresh".equals(resultType)) {
								if (!isGetListFirst) {
									showSimpleAlert("토너먼트 정보가 추가되어 다시 불러옵니다.");
								}
								contentMain.removeAllViews();
							}
							// 사진 한꺼번에 다운로드
							ImageDownloader imageDownloader = new ImageDownloader();
							int photoUrlArraySize = tournamentInfoLayoutList.size(); //실제 보여줄 만큼만.
							for (int i = 0; i < photoUrlArraySize; i++) {
								String photoUrl = photoUrlList.get(i);
								ImageView imgView = (ImageView) tournamentInfoLayoutList
										.get(i).findViewById(R.id.tourlist_photo);
								imageDownloader.download(photoUrl, imgView);
							}
							//화면에 레이아웃 추가
							contentMain.addView(contentMainInner);
							//'더보기' 버튼 셋팅
							if (isGetListFirst && (tournamentInfoLayoutList.size()==0)) {
								((ImageView)findViewById(R.id.btn_list_end)).setImageResource(R.drawable.img_tournament_list_view_empty);
							} else if (!isHaveMoreList) {
								((ImageView)findViewById(R.id.btn_list_end)).setImageResource(R.drawable.img_tournament_list_view_end);
							} else {
								((ImageView)findViewById(R.id.btn_list_end)).setImageResource(R.drawable.img_tournament_list_view_more);
							}
							((ImageView)findViewById(R.id.btn_list_end)).setVisibility(ImageView.VISIBLE);
							isGetListFirst = false;
							progressDialog.dismiss();
							showPopups();
							Log.d("tag", "화면 갱신 종료");
						}
					});
				}
				Log.d("tag", "sendTalkMessage() end");
			}
		};
		new Thread(runnable).start();
	}
	
	// 하나의 row를 만들기
	private RelativeLayout makeRelativeLayout(TournamentInfo tournamentInfo) {
		RelativeLayout tournamentListInfo = null;
		if ("M".equals(tournamentInfo.getGender())) {
			tournamentListInfo = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_main_tourlist_man, null);
		} else {
			tournamentListInfo = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_main_tourlist_woman, null);
		}
		
/*		//사진에 캡 씌워주기
		if ("".equals(memberid)) {
			//비로그인 일 때는 모두 캡
			((ImageView)tournamentListInfo.findViewById(R.id.tourlist_photo_cap)).setVisibility(ImageView.VISIBLE);
		} else if (gender.equals(tournamentInfo.getGender())) {
			//로그인 일 때는 동성만 캡
			((ImageView)tournamentListInfo.findViewById(R.id.tourlist_photo_cap)).setVisibility(ImageView.VISIBLE);
		}*/
		
		// 유저 인포 텍스트 변경
		TextView userInfo = (TextView)tournamentListInfo.findViewById(R.id.tourlist_userinfo_text);
		StringBuffer sb = new StringBuffer();
		sb.append(tournamentInfo.getTournamentMakerMemberid());
		sb.append(", ");
		sb.append(tournamentInfo.getLocal());
		if (tournamentInfo.getLocal_detail() != null) {
			if ( (!tournamentInfo.getLocal_detail().equals("")) && (!tournamentInfo.getLocal_detail().equals("null"))) {
				sb.append(" ");
				sb.append(tournamentInfo.getLocal_detail());
			}
		}
		sb.append(", ");
		sb.append(tournamentInfo.getAge());
		userInfo.setText(sb);

		// 토너먼트 ID 달아주기
		TextView tourID = (TextView)tournamentListInfo.findViewById(R.id.tournamentID);
		tourID.setText("" + tournamentInfo.getTournamentid());
		
		// 유어ID 달아주기
		TextView userID = (TextView)tournamentListInfo.findViewById(R.id.userID);
		userID.setText("" + tournamentInfo.getTournamentMakerMemberid());

		// 토너먼트 제목 변경
		TextView tourTitle = (TextView)tournamentListInfo.findViewById(R.id.tourinfo_title_text);
		tourTitle.setText(tournamentInfo.getTournamentTitle());

		// 참여자 수
		TextView participantCnt = (TextView)tournamentListInfo.findViewById(R.id.tourinfo_participant_cnt);
		// StringBuffer 초기화
		sb.setLength(0);
		// 재사용
		sb.append("[");
		sb.append(tournamentInfo.getParticipantCnt());
		sb.append("]");
		participantCnt.setText(sb);

		// 마감 시간
		TextView deadlineText = (TextView)tournamentListInfo.findViewById(R.id.tourinfo_deadline_text);
		deadlineText.setText(tournamentInfo.getDay() + " " + tournamentInfo.getHour() + "시 참여마감");

		// 사진 셋팅
		// StringBuffer 초기화
		sb.setLength(0);
		// 재사용
		sb.append(LovetoConstant.PHOTO_THUMB_URL);
		sb.append(tournamentInfo.getTournamentMakerMemberid());
		sb.append(".jpg");
		photoUrlList.add(sb.toString());

		//클릭 리스너 달기
		ImageView userphoto = (ImageView)tournamentListInfo.findViewById(R.id.tourlist_photo);
		userphoto.setOnClickListener(this); //사진
		userInfo.setOnClickListener(this); //유저정보텍스트
		RelativeLayout tournamentTitle = (RelativeLayout)tournamentListInfo.findViewById(R.id.tourinfo_talkbox);
		tournamentTitle.setOnClickListener(this); //말풍선
		ImageView userarrow = (ImageView)tournamentListInfo.findViewById(R.id.tourinfo_arrow);
		userarrow.setOnClickListener(this);

		return tournamentListInfo;
	}
	
	private void getNewMessage() {
		
		//비로그인 시 실행하지 않음.
		if ("".equals(memberid)) {
			return;
		}
		
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				
				try {
					
					StringBuffer URL = new StringBuffer();
					URL.append(LovetoConstant.MESSAGE_CHECK_NEW_URL);
					URL.append("?memberid=").append(memberid);
					Log.d("tag", "URL: " + URL.toString());
					//서버에서 정보 받아오기
					String jsonText = JsonUtils.getStringFromUrl(URL.toString());
					Log.d("tag", "jsonText: " + jsonText);
					JSONObject getObject = new JSONObject(jsonText);
					newMessageCnt = getObject.getInt("new_cnt");
					Log.d("tag", "newMessageCnt: " + newMessageCnt);
					not_select_winner_tournamentID = getObject.getInt("not_select_winner_tournamentID");
					Log.d("tag", "not_select_winner_tournamentID: " + not_select_winner_tournamentID);
					not_view_winner_tournamentID = getObject.getInt("not_view_winner_tournamentID");
					Log.d("tag", "not_view_winner_tournamentID: " + not_view_winner_tournamentID);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} catch (JSONException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} finally {
					// 풋터에 새 쪽지 개수 보여주기
					myHandler.post(new Runnable() {
						@Override
						public void run() {
							//풋터에 새로 받은 쪽지 개수 표시하기
							TextView vNewMsg = (TextView) findViewById(R.id.message_new_cnt);
							if (newMessageCnt !=0) {
								vNewMsg.setText("" + newMessageCnt);
								vNewMsg.setVisibility(TextView.VISIBLE);
							}
							if (not_select_winner_tournamentID != 0 || not_view_winner_tournamentID != 0) {
								showSimpleAlertForSelectOrViewWinner();
							}
						}
					});
				}
				Log.d("tag", "sendTalkMessage() end");
			}
		};
		new Thread(runnable).start();
	}
	
	private void setSpinner() {
		Log.d("tag", "스피너 세팅 시작");
		
		//지역 스피너 세팅하기
		TextView local_textview = (TextView) findViewById(R.id.local_textview);
		Spinner localspinner = (Spinner) findViewById(R.id.localspinner); 
		String[] localNameArray = getResources().getStringArray(R.array.local_name_array_for_spinner);
		List<String> localListForSpinner = new ArrayList<String>(); //스피너에 넣을 스트링 리스트
		ArrayAdapter<String> localAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,localListForSpinner); //스피너 어댑터
		localAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		localspinner.setAdapter(localAdapter);
		localspinner.setPrompt("보고싶은 지역을 선택하세요.");
		//스피너에 담을 데이터 설정
		for (int i=0;i<localNameArray.length;i++) {
			localListForSpinner.add(localNameArray[i]);
			if (localNameArray[i].equals(clientLocal)) {
				if (localNameArray[i].equals("전체지역")) {
					local_textview.setText("지역");
				} else {
					local_textview.setText(localNameArray[i]);
				}
			}
			if (localNameArray[i].equals(local) && (!local_detail.equals("null")) && (!local_detail.equals(""))) {
				localListForSpinner.add("내주변 (" + local_detail + ")");
			}
		}
		//스피너 선택 위치 결정
		int localSelectPosition = 0;
		for (int i=0;i<localListForSpinner.size();i++) {
			if (localListForSpinner.get(i).equals(clientLocal)) {
				localSelectPosition = i;
				if (localListForSpinner.get(i).equals("내주변 (" + local_detail + ")")) {
					isLocalSearchDetailStr = "Y";
					local_textview.setText(local_detail);
				}
			}
		}
		localAdapter.notifyDataSetChanged(); //동적 데이터 스피너에 반영하기
		localspinner.setSelection(localSelectPosition);  //선택 위치 반영
		
		//성별 스피너 세팅하기
		TextView gender_textview = (TextView) findViewById(R.id.gender_textview);
		Spinner genderspinner = (Spinner) findViewById(R.id.genderspinner);
		genderspinner.setPrompt("보고싶은 성별을 선택하세요.");
		String[] genderNameArray = getResources().getStringArray(R.array.gender_name_array);
		int genderSelectPosition = 0;
		for (int i=0;i<genderNameArray.length;i++) {
			if (genderNameArray[i].equals(clientGender)) {
				genderSelectPosition = i;
				if (genderNameArray[i].equals("전체성별")) {
					gender_textview.setText("성별");
				} else {
					gender_textview.setText(genderNameArray[i]);
				}
			}
		}
		genderspinner.setSelection(genderSelectPosition);
		
		//정렬 스피너 세팅하기
		TextView order_textview = (TextView) findViewById(R.id.order_textview);
		Spinner sortspinner = (Spinner) findViewById(R.id.sortspinner);
		sortspinner.setPrompt("정렬 기준을 선택하세요.");
		String[] sortNameArray = getResources().getStringArray(R.array.sorting_name_array);
		int sortSelectPosition = 0;
		for (int i=0;i<sortNameArray.length;i++) {
			if (sortNameArray[i].equals(clientOrder)) {
				sortSelectPosition = i;
				order_textview.setText(sortNameArray[i]);
			}
		}
		sortspinner.setSelection(sortSelectPosition);
		
	}
	
}
